#include "KeyboardInput.hpp"
#include "Lua.h"

KeyboardInput::KeyboardInput()
{
	m_active = false;
	m_maxInputSize = 100;
	m_string = "";
	SDL_EnableUNICODE(SDL_ENABLE);
}


KeyboardInput::~KeyboardInput()
{
	SDL_EnableUNICODE(SDL_DISABLE);
}

void KeyboardInput::PopBack()
{
	if(m_string.size() != 0)
		m_string.erase(m_string.length() - 1);
}

bool KeyboardInput::HandleEvents(const SDL_Event &event)
{
	if( event.type == SDL_KEYDOWN )
    {   

		if((event.key.keysym.sym == SDLK_RETURN) && (m_active == false))
		{
			ClearString();
			m_active = true;
		}

		else if(m_active)
		{
			//If the string less than maximum size
			if( m_string.length() <= m_maxInputSize )
			{
				if((event.key.keysym.unicode >= (Uint16)' ') && (event.key.keysym.unicode <= (Uint16)'~'))
					AddCharacter((char)event.key.keysym.unicode);
			}

			// backspace pressed 
			if((event.key.keysym.sym == SDLK_BACKSPACE))
				PopBack();
			

			

			// if enter was pressed
			if(event.key.keysym.sym == SDLK_RETURN)
			{
				m_active = false;

				// if we actually have a message to add
				if(m_string.size() > 0)
				{
					if(m_string.at(m_string.size() - 1) == '~')
					{
						string temp = m_string;
						temp.erase(temp.length() - 1);
						Lua->RunString(temp.c_str());
					}
					//ClearString();

					return true;
				}
				
			}
			
		}

		return false;
	}

	return false;
}